# @Time : 2024-11-06 18:07
# @Author : Fioman 
# @Phone : 13149920693
"""
future.cancel(): 取消Future代表的线程任务.如果任务已经开始执行,取消操作会失败并返回False.这个取消调用
的时候,如果配合running()也会出现取消失败的情况,所以取消之后一定要判断是否取消成功
future.cancelled(): 检查Future代表的线程是否被取消成功
"""
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def task():
    currentName = threading.current_thread().name
    print(f"{currentName} 开始")
    time.sleep(2)
    print(f"{currentName} 结束")
    return f"{currentName} 没有被取消"


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=5, thread_name_prefix="task_") as executor:
        futures = [executor.submit(task) for _ in range(10)]
        for index, future in enumerate(futures):
            future.cancel()
            if future.cancelled():
                print(f"Task_{index} 取消成功")
            else:
                print(f"Task_{index} 取消失败")

        for future in as_completed(futures):
            if not future.cancelled():
                print(future.result())
